#coding:utf-8
import sys

from thrift.protocol import TBinaryProtocol
from thrift.transport import TSocket
from thrift.transport import TTransport

from lib.Context import Context
from lib.JMTFramedTransport import JMTFramedTransport
from lib.JMTBinaryProtocol import JMTBinaryProtocol

sys.path.append('../gen-py')

class Client(object):
    """docstring for Client"""
    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.connect()

    def setClass(self, api):
        self.api = api
        return self

    def setMethod(self, method):
        self.method = method
        return self

    def getApi(self):
        module = self.api + '.' + self.api
        api = __import__(module)
        context = Context()
        context.put('serverName', self.api)
        context.put('methodName', self.method)
        self.transport.setContext(context)
        client = eval('api.' + self.api + '.Client(self.protocol)')
        self.transport.open()
        return client
        

    def connect(self):
        self.connect = TSocket.TSocket(self.ip, self.port)
        self.transport = JMTFramedTransport(self.connect)
        self.protocol = JMTBinaryProtocol(self.transport)
        
        